package com.imooc.o2o.service.impl;

import com.imooc.o2o.dao.ShopDao;
import com.imooc.o2o.dto.ShopExecution;
import com.imooc.o2o.entity.Shop;
import com.imooc.o2o.enums.ShopStateEnum;
import com.imooc.o2o.service.ShopService;
import com.imooc.o2o.util.FileUtil;
import com.imooc.o2o.util.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ShopServiceImpl implements ShopService{
    @Autowired
    private ShopDao shopDao;
    
    /**
     * 使用注解控制事务方法的优点： 1.开发团队达成一致约定，明确标注事务方法的编程风格
     * 2.保证事务方法的执行时间尽可能短，不要穿插其他网络操作，RPC/HTTP请求或者剥离到事务方法外部
     * 3.不是所有的方法都需要事务，如只有一条修改操作，只读操作不需要事务控制
     */
    @Transactional
    public ShopExecution addShop (Shop shop,InputStream shopImgInputStream, String fileName)throws RuntimeException{
        if(shop==null){
            return new ShopExecution(ShopStateEnum.NULL_SHOP_INFO);
        }
        try {
            //初始化店铺信息
            shop.setEnableStatus(0);
            shop.setCreateTime(new Date());
            shop.setLastEditTime(new Date());
            //添加店铺信息
            //shop是引用类型，Mybatis Mapper文件中“useGeneratedKeys”和“keyProperty”插入成功返回自动id将更新当前shop对象
            int effectedNum = shopDao.insertShop(shop);
            if (effectedNum <= 0) {
                throw new RuntimeException("店铺创建失败");
            } else {
                //添加店铺图片
                try {
                    if (shopImgInputStream != null) {
                        addShopImg(shop, shopImgInputStream,fileName);
                        //更新店铺的图片信息
                        effectedNum = shopDao.updateShop(shop);
                        if (effectedNum <= 0) {
                            throw new RuntimeException("创建图片地址失败");
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException("addShopImg error: "
                            + e.getMessage());
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("insertShop error: " + e.getMessage());
        }
        //ShopStateEnum是Shop类的扩展，主要是会店铺状态的注释，
        //可以这样理解ShopStateEnum的数据不回保存到数据库，而是辅助显示Shop类的信息，可以理解为是一种过滤加工数据的过程
        return new ShopExecution(ShopStateEnum.CHECK, shop);
    }
    private void addShopImg(Shop shop,InputStream shopImgInputStream,String fileName) {
        String dest = FileUtil.getShopImagePath(shop.getShopId());
        String shopImgAddr = ImageUtil.generateThumbnail(shopImgInputStream,fileName,dest);
        //shop是引用类型，这里是更新img图片信息
        shop.setShopImg(shopImgAddr);
    }
    public Shop queryByShopId(long shopId){
        return shopDao.queryByShopId(shopId);
    }
}
